<template>
  <div>
    <el-alert
          title="请输入有效的JSON数据，格式要求：{ nodes: [], edges: [] }"
          type="info"
          show-icon
          style="margin-bottom: 20px"
      />

      <div style="margin-bottom: 8px">
        <span>JSON 数据：</span>
        <span v-if="parsedJson" class="char-count">JSON大小: {{ calculateJsonSize(parsedJson) }}</span>
      </div>

      <el-input
          v-model="jsonInput"
          :autosize="{ minRows: 10, maxRows: 20 }"
          type="textarea"
          placeholder='{ "nodes": [], "edges": [] }'
          @input="validateJson"
      />

      <div class="validation-info">
        <el-alert
            v-if="validationError"
            :title="validationError"
            type="error"
            show-icon
            style="margin-top: 15px"
        />
        <div v-else-if="jsonInput.trim() !== '' && !validationError" style="margin-top: 15px">
          <el-alert
              :title="`数据验证通过！nodes 数量: ${nodesCount}, edges 数量: ${edgesCount}`"
              type="success"
              show-icon
          />
        </div>
      </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

const dialogVisible = ref(false)
const jsonInput = ref('')
const parsedJson = ref(null)
const validationError = ref('')
const nodesCount = ref(0)
const edgesCount = ref(0)

const isValidJson = computed(() => {
  return parsedJson.value && !validationError.value
})

const openDialog = () => {
  dialogVisible.value = true
  // 重置状态
  jsonInput.value = ''
  parsedJson.value = null
  validationError.value = ''
}

const validateJson = () => {
  validationError.value = ''
  if (jsonInput.value.trim() === '') {
    return
  }

  // 尝试解析JSON
  try {
    parsedJson.value = JSON.parse(jsonInput.value)
  } catch (e) {
    validationError.value = `JSON语法错误：${e.message}`
    return
  }

  // 验证数据结构
  if (!parsedJson.value) {
    validationError.value = "JSON格式错误：对象为空"
    return
  }

  const requiredKeys = ['nodes', 'edges']
  for (const key of requiredKeys) {
    if (!(key in parsedJson.value)) {
      validationError.value = `缺少必需的属性: ${key}`
      return
    }
  }

  if (!Array.isArray(parsedJson.value.nodes)) {
    validationError.value = "nodes 必须是一个数组"
    return
  }

  if (!Array.isArray(parsedJson.value.edges)) {
    validationError.value = "edges 必须是一个数组"
    return
  }

  // 统计节点和边数量
  nodesCount.value = parsedJson.value.nodes.length
  edgesCount.value = parsedJson.value.edges.length
}

const calculateJsonSize = (data) => {
  return new Blob([JSON.stringify(data)]).size + ' bytes'
}

const confirmJson = () => {
  if (isValidJson.value) {
    ElMessage.success(`成功提交JSON数据（${nodesCount.value}个节点, ${edgesCount.value}条边）`)
    // 这里实际使用时可以触发emit事件将数据传递出去
    dialogVisible.value = false
  } else {
    ElMessage.error('请先修正JSON错误')
  }
}
</script>

<style scoped>
.char-count {
  float: right;
  font-size: 12px;
  color: #888;
}

.validation-info {
  min-height: 50px;
}

:deep(.el-textarea__inner) {
  font-family: 'JetBrains Mono', 'Fira Code', Consolas, monospace;
  font-size: 14px;
}
</style>